<?php
namespace app\index\controller;
use app\common\controller\Base;//导入公共控制器
use app\common\model\ArtCate;
use app\common\model\Article;
use app\common\model\Comment;
use think\Db;
use think\facade\Request;

class Index extends Base
{
    //首页
    public function index()
    {
        if(empty($data['session_id'])){
            $this->error('你已登录',"index.php/index/user/login.html");
        }
        //全局查询条件
        $map = [];//将所有查询条件封装到数组中
        //条件1
        $map[] = ['status','=',1];//这里等号不可省略

        //实现搜索功能
        $keywords = Request::param('keywords');
        if(!empty($keywords)){
            //条件2
            $map[] = ['title','like','%'.$keywords.'%'];
        }

        //分类信息显示
        $cateId = Request::param('cate_id');

        //如果存在这个分类id
        if(isset($cateId)){
            //条件3
            $map[] = ['cate_id','=',$cateId];

            $res = ArtCate::get($cateId);
            $artList = Db::table('zh_article')
                ->where($map)
                ->order('create_time','desc')
                ->paginate(4,false,['query'=>request()->param()]);//搜索后可点击下一页，结果保留

            $this->view->assign('cateName',$res->name);
        }else{
            $this->view->assign('cateName','全部');
            $artList = Db::table('zh_article')
                ->where($map)
                ->order('create_time', 'desc')
                ->paginate(4,false,['query'=>request()->param()]);
        }
        $this->view->assign('empty','<h3>没有文章</h3>');

        $this->view->assign('artList',$artList);
        return $this->fetch('index',['title'=>'社区问答']);
    }

    //添加文章界面
    public function insert(){
        //1用户必须登录才可以发布文章
        $this->isLogin();
        //2设置页面标题
        $this->view->assign('title','发布文章');
        //3获取栏目信息
        $cateList = ArtCate::where('status',1)->select();//查询数据
//        halt($careList);
        if(count($cateList) > 0){
            //将查询到的信息传给模板
            $this->assign('cateList',$cateList);
        }else{
            $this->error('请先添加栏目','index/index');
        }
        //4发布界面渲染
        return $this->view->fetch('insert');
    }

    //保存文章
    public function save(){
        if(Request::isPost()){
            //1获取用户提交的文章信息
                $data = Request::post();
//                halt($data);
            $rule = 'app\common\validate\Article';
            $res = $this->validate($data,$rule);
            if(true!==$res){
                //验证失败
                echo '<script>alert("'.$res.'");location.back()</script>';
            }else{
                //验证成功
                //获取上传的图片信息
                $file = Request::file('title_img');
                //文件信息一验证，验证成功后再上传到服务器指定目录以public为起始目录
                $info = $file->validate([
                    'size'=>1000000000,
                    'exi'=>'jpeg,jpg,png,gif',
                ])->move('uploads/');
                if($info){
                    $data['title_img'] = $info->getSaveName();
                }else{
                    $this->error($file->getError(),'index/index/insert');
                }
                //将数据写到数据库
                if(Article::create($data)){
                    $this->success('发布成功','index/index');
                }else{
                    $this->error('文章保存失败');
                }

            }
        }else{
            $this->error('请求类型错误');
        }
    }

    //详情页
    public function detail(){
        $artId = Request::param('id');
        $art = Article::get(function ($query) use($artId){
            $query->where('id','=',$artId)->setInc('pv');
        });
        if(!is_null($art)){
            $this->view->assign('art',$art);
        }

        //添加评论显示
        $comList = Db::table('zh_user_comments')
            ->where('status',1)
            ->where('article_id',$artId)
            ->order('create_time','desc')
            ->paginate(5,false,['query'=>request()->param()]);

        $this->assign('commentList',$comList);

        $this->view->assign('title','详情页');
        return $this->view->fetch('detail');
    }

    //收藏
    public function fav(){
        if(!Request::isAjax()){
            return ['status'=>-1,'message'=>'请求类型错误'];
        }

        //获取从前端传递过来的数据
        $data = Request::param();
//        halt($data);//查看方式：F12 network fav.html

        //判断用户是否登录
        if(empty($data['session_id'])){
            return ['status'=>-2,'message'=>'请登录后收藏'];
        }
        //查询条件
        $map[] = ['user_id','=',$data['user_id']];
        $map[] = ['article_id','=',$data['article_id']];

        $fav = Db::table('zh_user_fav')->where($map)->find();
        if(is_null($fav)){
            Db::table('zh_user_fav')->data([
                'user_id'=>$data['user_id'],
                'article_id'=>$data['article_id'],
            ])->insert();
            return ['status'=>1,'message'=>'收藏成功'];
        }else{
            Db::table('zh_user_fav')->where($map)->delete();
            return ['status'=>0,'message'=>'已取消'];
        }
    }

    //点赞
    public function ok(){
        if(!Request::isAjax()){
            return ['status'=>-1,'message'=>'请求类型错误'];
        }

        //获取从前端传递过来的数据
        $data = Request::param();
//        halt($data);//查看方式：F12 network fav.html

        //判断用户是否登录
        if(empty($data['session_id'])){
            return ['status'=>-2,'message'=>'请登录后点赞'];
        }
        //查询条件
        $map[] = ['user_id','=',$data['user_id']];
        $map[] = ['art_id','=',$data['article_id']];

        $fav = Db::table('zh_user_like')->where($map)->find();
        if(is_null($fav)){
            Db::table('zh_user_like')->data([
                'user_id'=>$data['user_id'],
                'art_id'=>$data['article_id'],
            ])->insert();
            return ['status'=>1,'message'=>'已赞'];
        }else{
            Db::table('zh_user_like')->where($map)->delete();
            return ['status'=>0,'message'=>'点赞'];
        }
    }

    //评论
    public function insertComment(){
        if(Request::isAjax()){
            //获取评论
            $data = Request::param();
//            halt($data);

            //判断用户是否登录
            if(empty($data['user_id'])){
                return ['status'=>-2,'message'=>'请登录后评论'];
            }

            //将用户保存到表中
            if(Comment::create($data,true)){//true:过滤不在数据表中的字段
                return ['status'=>1,'message'=>'评论发布成功'];
            }else{
                return ['status'=>0,'message'=>'评论发布失败'];
            }
        }

    }
}
